import { Column, BeforeInsert, BeforeUpdate } from "typeorm";
import { ManualTimestamp } from "../decorators/manual-timestamp.decorator";

/**
 * 基础实体类
 * 提供自动时间戳功能，兼容MySQL 5.5
 */
export abstract class BaseEntity {
  @Column("datetime", { name: "created_at", comment: "创建时间" })
  created_at!: Date;

  @Column("datetime", {
    name: "updated_at",
    comment: "更新时间",
    nullable: true,
  })
  updated_at!: Date | null;

  @BeforeInsert()
  beforeInsert() {
    // 如果created_at为空，设置为当前时间
    if (this.created_at === null || this.created_at === undefined) {
      this.created_at = new Date();
    }
  }

  @BeforeUpdate()
  beforeUpdate() {
    // 设置updated_at为当前时间
    this.updated_at = new Date();
  }
}

/**
 * 基础实体类（仅创建时间）
 * 适用于只需要创建时间的实体
 */
export abstract class BaseCreatedEntity {
  @Column("datetime", { name: "created_at", comment: "创建时间" })
  created_at!: Date;

  @BeforeInsert()
  beforeInsert() {
    // 如果created_at为空，设置为当前时间
    if (this.created_at === null || this.created_at === undefined) {
      this.created_at = new Date();
    }
  }
}

/**
 * 基础实体类（仅更新时间）
 * 适用于只需要更新时间的实体
 */
export abstract class BaseUpdatedEntity {
  @Column("datetime", {
    name: "updated_at",
    comment: "更新时间",
    nullable: true,
  })
  updated_at!: Date | null;

  @BeforeUpdate()
  beforeUpdate() {
    // 设置updated_at为当前时间
    this.updated_at = new Date();
  }
}
